package com.snail.billing.net;

import java.security.MessageDigest;
import java.util.Locale;

public class BillingEncode {

	public static String enCode(String source, String charsetName) {
		try {
			byte[] bsrc = source.getBytes(charsetName);
			String dest = "", str;
			if (bsrc == null) {
				return "";
			}
			for (byte bb : bsrc) {
				int num = (bb >= 0 ? bb : (bb & 0x7F) + (1 << 7));
				str = Integer.toHexString(num);
				if (str.length() < 2) {
					str = "0" + str;
				}
				dest += str.toUpperCase(Locale.getDefault());
			}
			return dest;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	public static String MD5(String origin) {
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(origin.getBytes("UTF-8"));
			return new String(toHex(digest.digest(), false));
		} catch (Exception e) {
			// ignore
		}
		return "";
	}

	private static char[] toHex(byte[] data, boolean toLowerCase) {
		char[] toDigits = toLowerCase ? DIGITS_LOWER : DIGITS_UPPER;
		int l = data.length;
		char[] out = new char[l << 1];
		// two characters form the hex value.
		for (int i = 0, j = 0; i < l; i++) {
			out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
			out[j++] = toDigits[0x0F & data[i]];
		}
		return out;
	}
}
